package com.cosmic.pizza.dao.Impl;

import com.cosmic.pizza.dao.UserDao;
import com.cosmic.pizza.pojo.User;
import com.cosmic.pizza.util.JDBCUtils;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.List;

public class UserDaoImpl implements UserDao {
    private JdbcTemplate jdbcTemplate = new JdbcTemplate(JDBCUtils.getDataSource());
    @Override
    public User findUserByUsernameAndPassword(String username, String password) {
        String sql = "select * from tab_user where username = ? and password = ?";
        try {
            User user = jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<User>(User.class), username, password);
            return user;
        } catch (Exception e) {
            return null;
        }
    }

    @Override
    public int saveUser(User user) {
        String sql = "insert into tab_user" +
                "(username, password, name, sex, telephone, email, status, code) " +
                "values(?,?,?,?,?,?,?,?)";
        return jdbcTemplate.update(sql, user.getUsername(), user.getPassword(),
                user.getName(), user.getSex(),
                user.getTelephone(), user.getEmail(), user.getStatus(), user.getCode());
    }

    @Override
    public User findUserByUsername(String username) {
        String sql = "select * from tab_user where username = ?";
        List<User> list = jdbcTemplate.query(sql, new BeanPropertyRowMapper<User>(User.class), username);
        return list.size() == 0 ? null:list.get(0);
    }

    @Override
    public int setUserStatus(String code) {
        String sql = "update tab_user set status = 'Y' where code = ?";
        return jdbcTemplate.update(sql, code);
    }
}
